package com.google.jacli;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import com.google.jacli.l10n.BundleUtil;

public class DefaultUsage implements Usage {

    private Map<Class, ResourceBundle> bundleMaps = new HashMap<Class, ResourceBundle>();
    
    public void print(CommandLine commandLine) {
        StringBuffer buffer = new StringBuffer();
        ResourceBundle bundle = null;

        if (commandLine.getPattern() == Pattern.OPT) {
            for (Field field : commandLine.getFields()) {
                Argument argument = CommandLineParser.getArgument(field);

                bundle = bundleMaps.get(field.getDeclaringClass());
                if (bundle == null) {
                    try {
                        bundle = BundleUtil.getBundle(field.getDeclaringClass());
                    } catch (MissingResourceException e) {
                        // ignore the exception
                    }
                    bundleMaps.put(field.getDeclaringClass(), bundle);
                }

                if (!argument.required()) {
                    buffer.append("[");
                }

                if (argument.option().length() == 0) {
                    // the last argument
                    continue;
                }

                if (argument.shortName().length() > 0) {
                    buffer.append(commandLine.getShortPrefix());
                    buffer.append(argument.shortName());
                    buffer.append(", ");
                }
                buffer.append(commandLine.getPrefix() + argument.option());
                buffer.append(getDots(argument.option().length()));

                if (argument.documentation().length() > 0) {
                    if (bundle != null) {
                        try {
                            buffer.append(bundle.getString(argument.documentation()));
                        } catch (MissingResourceException e) {
                            buffer.append(argument.documentation());
                        }
                    } else {
                        buffer.append(argument.documentation());
                    }

                } else {
                    buffer.append("N/A");                        
                }
                if (!argument.required()) {
                    buffer.append("]");
                }
                buffer.append("\n");
            }
        }
        System.out.println(buffer);
    }

    private String getDots(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 20 - length; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }
}